package example.telosys.persistence;

import org.demo.vo.bean.Country;
import org.demo.vo.bean.Publisher;
import org.telosys.persistence.PersistenceManager;
import org.telosys.persistence.PersistenceManagerFactory;
import org.telosys.persistence.TelosysPersistence;

public class LoadLink {

	public static void main(String[] args) {
		
		
		PersistenceManagerFactory pmf = TelosysPersistence.getPersistenceManagerFactory() ;
		PersistenceManager pm = pmf.createPersistenceManager() ;
		
		Publisher p ;
		if ( ( p = pm.loadByKey(Publisher.class, 4) ) != null ) {
			System.out.println("Found : " + p);
			
			//--- Load link "ManyToOne"
			String countryCode = p.getCountryCode();
			if ( countryCode != null ) {
				Country c = pm.loadByKey(Country.class, countryCode ) ;
				if ( c != null ) {
					System.out.println("Publisher country : " + c );
				}
				else {
					System.out.println("Publisher country not found" );
				}
			}
			else {
				System.out.println("No country for this publisher " );
			}
			
			Object oLink = loadLink(pm, p);
			
			System.out.println("loadLinkManyToOne : " + oLink );
			
			//--- Same operation with pm 
//			System.out.println("-------- load link with PM (without link name)" );
//			{
//				Country c = pm.loadLink(Country.class, p ) ;
//				if ( c != null ) {
//					System.out.println("Publisher country : " + c );
//				}
//				else {
//					System.out.println("Publisher country not found" );
//				}
//			}

			System.out.println("-------- load link with PM (with link name)" );
			{
				Country c = pm.loadLink(Country.class, p, "country" ) ;
				if ( c != null ) {
					System.out.println("Publisher country : " + c );
				}
				else {
					System.out.println("Publisher country not found" );
				}
			}
			
		}
		else {
			System.out.println("Not found");
		}
		
		pm.close();		
	}

	// Many to One
	private static Object loadLink(PersistenceManager pm, Publisher entity ) {
		
		Class<?> expectedType = Country.class ;
		String countryCode = entity.getCountryCode();
		
		// for each key part ...
		Object[] keyParts = new Object[1] ;
		keyParts[0] = countryCode ;
		
		// check at least one key part not null 
		boolean oneKeyPartNotNull = false ;
		for ( Object o : keyParts ) {
			if ( o != null ) {
				oneKeyPartNotNull = true ;
			}
		}
		
		Object o = null ;
		if ( oneKeyPartNotNull ) {
			o = pm.loadByKey(expectedType, keyParts ) ;
			if ( o != null ) {
				System.out.println("Link found : " + o );
			}
			else {
				System.out.println("Link not found" );
			}
		}
		else {
			System.out.println("All key parts are null " );
		}
		return o ;
	}
	
}
